#! /bin/bash

source ./function.sh


# pt-osc 工具执行
exec_ptosc() {
    # exec_ptosc "sql_info"
    local sql_info="$1"

    local table_name="$(sql_processing "table_name" "$sql_info")"
    local alter="$(echo "$sql_info"|sed -nE 's/alter\s+table\s+(`?[a-zA-Z0-9_]+`?\.)?(`?[a-zA-Z0-9_]+`?)\s+(.*);/\3/Ip')"
    local charset="$(${MYSQL_CONN} ${MYSQL_DATABASE} -N -e "show create table ${table_name};" 2>/dev/null |sed -nE 's/.*create\s+table\s+`\w+`\s+\(.*\)\s+.*\s+CHARSET=(.*).*/\1/Ip')"

    if [ "$PTOSC_check_replication_filters" == 'yes' ];then
        PTOSC_check_replication_filters='--check-replication-filters'
    elif [ "$PTOSC_check_replication_filters" == 'no' ];then
        PTOSC_check_replication_filters='--no-check-replication-filters'
    else
        PTOSC_check_replication_filters=''
    fi


    if [ "$PTOSC_check_unique_key_change" == 'yes' ];then
        PTOSC_check_unique_key_change='--check-unique-key-change'
    elif [ "$PTOSC_check_unique_key_change" == 'no' ];then
        PTOSC_check_unique_key_change='--no-check-unique-key-change'
    else
        PTOSC_check_unique_key_change=''
    fi

    if [ "$PTOSC_check_slave_lag" == 'yes' ];then
        PTOSC_check_slave_lag="--check-slave-lag --max-lag=${PTOSC_max_lag}"
    elif [ "$PTOSC_check_slave_lag" == 'no' ];then
         PTOSC_check_slave_lag='--skip-check-slave-lag '
    else
        PTOSC_check_slave_lag=''
    fi

    if [ "$PTOSC_drop_old_table" == 'yes' ];then
        PTOSC_drop_old_table='--drop-old-table'
    elif [ "$PTOSC_drop_old_table" == 'no' ];then
        PTOSC_drop_old_table='--no-drop-old-table'
    else
        PTOSC_drop_old_table=''
    fi


    local ptosc="${PTOSC_COMMAND_PATH} \
    --print --statistics \
    --progress time,30 \
    --preserve-triggers \
    --pause-file=${PTOSC_pause_file} \
    u=${PTOSC_USER},p=${PTOSC_PASSWORD},h=${PTOSC_HOST},P=${PTOSC_PORT},D=${MYSQL_DATABASE},t=${table_name} \
    --alter-foreign-keys-method=${PTOSC_alter_foreign_keys_method} \
    --chunk-size=${PTOSC_chunck_size} \
    --max-load=${PTOSC_max_load} \
    --critical-load=${PTOSC_critical_load} \
    ${PTOSC_check_replication_filters} \
    ${PTOSC_check_unique_key_change} \
    ${PTOSC_check_slave_lag} \
    ${PTOSC_drop_old_table} \
    --recursion-method=${PTOSC_recursion_method} \
    --charset=${charset} \
    "

    # 测试执行
    $ptosc --alter="${alter}"   --dry-run >${ALTER_LOG} 2>&1
    if [ $? -eq 0 ];then
        # 正式执行
        nohup $ptosc --alter="${alter}"  --execute >${ALTER_LOG} 2>&1 &
        if [ $? -eq 0 ];then
            echo 1
        else
            echo 0
        fi
    else
        echo 0
    fi

}


